package com.example.happytime;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class JokeFragment extends BaseFragment {

  PullToRefreshListView jokeLv;
    List<String> data;
   ArrayAdapter<String>adapter;
   int page=1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_joke, container, false);
        jokeLv=view.findViewById(R.id.joke_lv);
        //数据源
        data=new ArrayList<>();
        //适配器
        adapter=new ArrayAdapter<String>(getContext(),R.layout.item_joke,R.id.item_joke_tv,data);
        jokeLv.setAdapter(adapter);
       String url=getJokeUrl(page);
       connectNetwork(url);
       setRefresh();
        return view;
    }
    Handler handler=new Handler(){
        public void handleMessage(Message msg){
            if (msg.what==1){
                jokeLv.onRefreshComplete();
            }
        }
    };

    private void setRefresh() {
        jokeLv.setMode(PullToRefreshBase.Mode.BOTH);
        jokeLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                handler.sendEmptyMessageDelayed(1,500);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                String jokeUrl=getJokeUrl(page);
                connectNetwork(jokeUrl);

            }
        });
    }

    private String getJokeUrl(int page) {
       // String key="51c56dff43f88bb2f78c3573c70b3003";
        String key="680ca9398eb1a6304d1ab411b66e58a1";
        String url = "http://v.juhe.cn/joke/content/list.php?key="+key+"&page="+page+"&pagesize=10&sort=asc&time=1418745237";
        return url;
    }

    @Override
    public void onSuccess(String result) {
        JokeBean jokeBean=new Gson().fromJson(result,JokeBean.class);
        List<JokeBean.ResultBean.DataBean>list=jokeBean.getResult().getData();
        for(int i=0;i<list.size();i++){
            String s=list.get(i).getContent();
            data.add(s);
        }
        adapter.notifyDataSetChanged();
        jokeLv.onRefreshComplete();
    }
}
